package com.hdu.h_health.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.hdu.h_health.Adapter.WeeklyAdapter;
import com.hdu.h_health.CycleViewPager;
import com.hdu.h_health.MyApplication;
import com.hdu.h_health.R;
import com.hdu.h_health.ViewFactory;
import com.hdu.h_health.bean.ADInfo;
import com.hdu.h_health.bean.WeeklyBean;
import com.hdu.h_health.ui.ConsultTestActivity;
import com.hdu.h_health.ui.ConsultUniActivity;
import com.hdu.h_health.ui.ConsultZXActivity;
import com.hdu.h_health.ui.MainActivity;
import com.hdu.h_health.ui.MyActivity;
import com.hdu.h_health.ui.WeeklyDetailsActivity;
import com.hdu.h_health.utils.CommonUtils;
import com.hdu.h_health.widget.ListViewInScroll;
import com.hdu.h_health.widget.NavigationView;
import com.squareup.leakcanary.RefWatcher;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

/**
 * 咨询界面
 * Created by See on 2016/2/25.
 */
public class ConsultFragment extends Fragment implements View.OnClickListener {

    private LinearLayout ConsultZXButton;//咨询预约按钮

    private LinearLayout ConsultUniButton;//高校入口按钮

    private LinearLayout ConsultXSButton;//心事按钮

    private LinearLayout ConsultTestButton;//心理测试按钮

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener;

    private CycleViewPager cycleViewPager;//轮播图

    private ListViewInScroll listView;

    private WeeklyAdapter adapter;

    private List<ImageView> views = new ArrayList<ImageView>();

    private List<ADInfo> infos = new ArrayList<ADInfo>();

    private List<WeeklyBean> weeklyBeans = new ArrayList<WeeklyBean>();

    private String[] imageUrls = {
            "http://7xt09p.com1.z0.glb.clouddn.com/banner1.png",
            "http://7xt09p.com1.z0.glb.clouddn.com/banner2.png",
            "http://7xt09p.com1.z0.glb.clouddn.com/banner3.png",
            "http://7xt09p.com1.z0.glb.clouddn.com/banner4.png",
            "http://7xt09p.com1.z0.glb.clouddn.com/banner5.png"};

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_consult, container, false);
        initView(v);
        initViewPager();
        initListView();
        queryWeekly();
        return v;
    }

    private void initView(View v) {
        cycleViewPager = (CycleViewPager) getChildFragmentManager().findFragmentById(R.id.fragment_cycle_viewpager_content);
        listView = (ListViewInScroll) v.findViewById(R.id.consult_listView);
        ConsultZXButton = (LinearLayout) v.findViewById(R.id.consult_zixun_button);
        ConsultZXButton.setOnClickListener(this);
        ConsultUniButton = (LinearLayout) v.findViewById(R.id.consult_uni_button);
        ConsultUniButton.setOnClickListener(this);
        ConsultTestButton = (LinearLayout) v.findViewById(R.id.consult_test_button);
        ConsultTestButton.setOnClickListener(this);
        ConsultXSButton = (LinearLayout) v.findViewById(R.id.consult_xinshi_button);
        ConsultXSButton.setOnClickListener(this);
    }

    //初始化ViewPager
    private void initViewPager() {
        for (int i = 0; i < imageUrls.length; i++) {
            ADInfo info = new ADInfo();
            info.setUrl(imageUrls[i]);
            info.setContent("图片-->" + i);
            infos.add(info);
        }

        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(getActivity(), infos.get(infos.size() - 1).getUrl()));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(this.getActivity(), infos.get(i).getUrl()));
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(this.getActivity(), infos.get(0).getUrl()));
        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);

        mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {
            @Override
            public void onImageClick(ADInfo info, int position, View imageView) {
                if (cycleViewPager.isCycle()) {
                    position = position - 1;
                    Toast.makeText(getActivity(),
                            "position-->" + info.getContent(), Toast.LENGTH_SHORT)
                            .show();
                }
            }
        };

        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, infos, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(true);
        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(3000);
        //设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();

    }

    //初始化ListView
    private void initListView() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Bundle bundle = new Bundle();
                bundle.putSerializable("weeklyBean", weeklyBeans.get(position));
                Intent i = new Intent();
                i.putExtras(bundle);
                i.setClass(getContext(), WeeklyDetailsActivity.class);
                startActivity(i);
            }
        });
        adapter = new WeeklyAdapter(getContext(), weeklyBeans);
        listView.setAdapter(adapter);
        //让ListView失去焦点，使得ScrollView回滚到顶部
        listView.setFocusable(false);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.consult_zixun_button:
                intent.setClass(getActivity(), ConsultZXActivity.class);
                ConsultFragment.this.startActivity(intent);
                break;
            case R.id.consult_uni_button:
                intent.setClass(getActivity(), ConsultUniActivity.class);
                ConsultFragment.this.startActivity(intent);
                break;
            case R.id.consult_xinshi_button://心事
                showPrivateFragment();
                break;
            case R.id.consult_test_button:
                intent.setClass(getActivity(), ConsultTestActivity.class);
                ConsultFragment.this.startActivity(intent);
                break;
            default:
                break;
        }
    }

    //跳转到心事视图
    private void showPrivateFragment() {
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.setChoiceItem(2);
    }

    //查询周刊列表
    private void queryWeekly() {
        BmobQuery<WeeklyBean> query = new BmobQuery<WeeklyBean>();
        query.setLimit(5);
        query.findObjects(getActivity(), new FindListener<WeeklyBean>() {
            @Override
            public void onSuccess(List<WeeklyBean> list) {
                if (list.size() > 0) {
                    if (weeklyBeans.size() > 0) {
                        weeklyBeans.clear();
                    }
                    for (WeeklyBean bean : list) {
                        weeklyBeans.add(bean);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(int i, String s) {
                CommonUtils.showToast(getActivity(), i + s);
            }
        });
    }

    /**
     * 动态设置ListView的高度
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null) {
            return;
        }
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View item = listAdapter.getView(i, null, listView);
            item.measure(0, 0);
            totalHeight += item.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        //总高度
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = MyApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }
}